package obecto.task
{
	import flash.display.DisplayObject;
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.ProgressEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	import obecto.task.progress.IProgressiveTask;
	
	[Event(name="start", type="obecto.event.TaskEvent")]
	[Event(name="complete", type="obecto.event.TaskEvent")]
	[Event(name="progress", type="flash.events.ProgressEvent")]
	
	public class LoaderTask extends BaseTask implements IProgressiveTask
	{
		private var _progress : Number;
		public function get progress():Number
		{
			return 0;
		}
		
		private var _loader : Object;
		public function set loader(value : Object) : void
		{
			if (value && (value is URLLoader || value is Loader))
			{
				if (_loader)
				{
					removeLoaderListeners();
				}
						
				_loader = value;
			
				if (_loader)
				{
					addLoaderListeners();
				}
			}
		}
		
		public function get loaderContent() : Object
		{
            if (_loader is URLLoader) return _loader.data;
            
			return _loader.content;
		}
		
		private var _request : URLRequest;
		public function set request(value : URLRequest) : void
		{
			_request = value;
		}
		
		public function LoaderTask(loader : Object = null)
		{
			super();
			
			if (loader && (loader is URLLoader || loader is Loader))
			{
				_loader = loader;
				addLoaderListeners();
			}
		}
		
		override protected function startActual() : void
		{
			if (_loader)
				_loader.load(_request);
		}
		
		private function addLoaderListeners() : void
		{
			if (_loader is Loader)
			{
				_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, handleLoaderComplete);
				_loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, handleLoaderProgress);
			}
			else if (_loader is URLLoader)
			{
				_loader.addEventListener(Event.COMPLETE, handleLoaderComplete);
				_loader.addEventListener(ProgressEvent.PROGRESS, handleLoaderProgress);
			}
		}
		
		private function removeLoaderListeners() : void
		{
			if (_loader is Loader)
			{
				_loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, handleLoaderComplete);
				_loader.contentLoaderInfo.removeEventListener(ProgressEvent.PROGRESS, handleLoaderProgress);
			}
			else if (_loader is URLLoader)
			{
				_loader.removeEventListener(Event.COMPLETE, handleLoaderComplete);
				_loader.removeEventListener(ProgressEvent.PROGRESS, handleLoaderProgress);
			}			
		}
		
		private function handleLoaderComplete(event : Event) : void
		{
			_progress = 100;
			complete();
		}
		
		private function handleLoaderProgress(event : ProgressEvent) : void
		{
			_progress = (event.bytesLoaded / event.bytesTotal) * 100;
			
			dispatchEvent(new ProgressEvent(ProgressEvent.PROGRESS, false, false, _progress, 100));
		}
	}
}